package zhihui.mobile.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.zgm.utils.FileUtils;
import com.zgm.utils.SharedPreferencesUtis;

import org.xutils.x;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import zhihui.mobile.R;
import zhihui.mobile.bean.user.UserInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.manager.AllManagerObvs;
import zhihui.mobile.manager.user.UserManager;
import zhihui.mobile.receiver.ExampleUtil;
import zhihui.mobile.uitils.CheckUtils;

/**
 * Created by 张公铭 on 2017/6/19 0019.
 */

public class MyApplication extends Application
{
    private static List<Activity> mActivities = Collections.synchronizedList(new LinkedList<Activity>());

    @Override
    public void onCreate()
    {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true);
        registerActivityListener();
        CheckUtils.initContext(getApplicationContext());

        //极光推送初始化
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
        JPushInterface.getRegistrationID(getApplicationContext());
        Config.Imei = ExampleUtil.getImei(getApplicationContext(), "");

        initImageLoader();

        initUser();
    }

    /**
     * 初始化账户信息
     */
    private void initUser()
    {
        UserInfo curUser = (UserInfo) SharedPreferencesUtis.getObjectFromShare(getBaseContext(), Config.USER_DATA_SAVE, Config.USER_DATA_SAVE);
        if (curUser != null)
        {
            UserManager.getInstance().setCurUser(curUser);
        }
    }

    private void initImageLoader()
    {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.default_img)
                .showImageForEmptyUri(R.drawable.default_img)
                .showImageOnFail(R.drawable.img_error)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(true)
                .displayer(new FadeInBitmapDisplayer(200))
                .build();

        File dir = new File(FileUtils.getDir().getPath() + Config.cache);
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                // 设置显示图片线程池大小，默认为3
                // 注:如果设置了taskExecutor或者taskExecutorForCachedImages 此设置无效
                .threadPoolSize(5)
                // 设置图片加载线程的优先级,默认为Thread.NORM_PRIORITY-1
                // 注:如果设置了taskExecutor或者taskExecutorForCachedImages 此设置无效
                .threadPriority(Thread.NORM_PRIORITY - 1) // default
                // 设置拒绝缓存在内存中一个图片多个大小 默认为允许,(同一个图片URL)根据不同大小的imageView保存不同大小图片
                .denyCacheImageMultipleSizesInMemory()
                // 设置内存缓存 默认为一个当前应用可用内存的1/8大小的LruMemoryCache
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                // 设置内存缓存的最大大小 默认为一个当前应用可用内存的1/8
                .memoryCacheSize(2 * 1024 * 1024)
                // 设置内存缓存最大大小占当前应用可用内存的百分比 默认为一个当前应用可用内存的1/8
                .memoryCacheSizePercentage(13) // default
                // 设置硬盘缓存
                .diskCache(new UnlimitedDiskCache(dir)) //缓存路径
                .diskCacheSize(50 * 1024 * 1024)
                .defaultDisplayImageOptions(options)
                .build();

        ImageLoader.getInstance().init(configuration);
    }

    private void registerActivityListener()
    {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks()
        {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState)
            {
                pushActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity)
            {

            }

            @Override
            public void onActivityResumed(Activity activity)
            {

            }

            @Override
            public void onActivityPaused(Activity activity)
            {

            }

            @Override
            public void onActivityStopped(Activity activity)
            {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState)
            {

            }

            @Override
            public void onActivityDestroyed(Activity activity)
            {
                if (null == mActivities && mActivities.isEmpty())
                {
                    return;
                }
                if (mActivities.contains(activity))
                {
                    /**
                     *  监听到 Activity销毁事件 将该Activity 从list中移除
                     */
                    popActivity(activity);
                }
            }
        });
    }

    /**
     * 添加一个Activity到管理
     *
     * @param activity
     */
    private void pushActivity(Activity activity)
    {
        mActivities.add(activity);
    }

    /**
     * 删除一个activity
     *
     * @param activity
     */
    private void popActivity(Activity activity)
    {
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity)
    {
        if (mActivities == null || mActivities.isEmpty())
        {
            return;
        }
        if (activity != null)
        {
            mActivities.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定的activity
     *
     * @param cls
     */
    public static void finishActivity(Class<?> cls)
    {
        if (mActivities == null || mActivities.isEmpty())
        {
            return;
        }
        for (Activity activity : mActivities)
        {
            if (activity.getClass().equals(cls))
            {
                finishActivity(activity);
            }
        }
    }

    /**
     * 找到指定的activity
     */
    public static Activity findActivty(Class<?> cls)
    {
        if (mActivities == null || mActivities.isEmpty())
        {
            return null;
        }
        for (Activity activity : mActivities)
        {
            if (activity.getClass().equals(cls))
            {
                return activity;
            }
        }
        return null;
    }

    /**
     * 获得顶层的activity
     */
    public Activity getTopActivity()
    {
        if (mActivities == null || mActivities.isEmpty())
        {
            return null;
        }
        Activity mBaseActivity = null;
        synchronized (mActivities)
        {
            final int size = mActivities.size() - 1;
            if (size < 0)
            {
                return null;
            }
            mBaseActivity = mActivities.get(size);
        }
        return mBaseActivity;
    }

    /**
     * 结束当前所有activity
     */
    public static void finishAllActivity()
    {
        if (mActivities == null || mActivities.size() == 0)
        {
            return;
        }
        for (Activity activity : mActivities)
        {
            activity.finish();
        }
        mActivities.clear();
    }

    /**
     * 退出
     */
    public static void appExit()
    {
        AllManagerObvs.getInstance().logout();
        finishAllActivity();
        System.exit(0);
    }
}
